package simplescenegraph.assets.models.obj;

import java.util.ArrayList;
import java.util.List;

import simplescenegraph.PolygonMesh;
import simplescenegraph.math.Vector2f;
import simplescenegraph.math.Vector3f;
import simplescenegraph.math.Vertex3f;

public class OBJFace extends PolygonMesh implements OBJElement {
	
	private OBJGroup group;
	
	private List<Integer> positionIndexes = new ArrayList<Integer>();
	
	private List<Integer> normalIndexes = new ArrayList<Integer>();
	
	private List<Integer> uvCoordinateIndexes = new ArrayList<Integer>();
	
	public OBJFace(OBJGroup group) {
		super(Mode.POLYGON);
		
		if (group == null) {
			throw new IllegalArgumentException();
		}
		
		this.group = group;
		this.group.addElement(this);
	}
	
	@Override
	public void prepare(boolean calculateVertexesNormals) {
		this.leafNode = group.getLeafNode();
		
		List<Vector3f> points = new ArrayList<Vector3f>();
		for (int i = 0; i < positionIndexes.size(); i++) {
			Vector3f position = group.getPositionByIndex(positionIndexes.get(i) - 1);
			
			Vector3f normal;
			if (normalIndexes.size() > 0) {
				normal =  group.getNormalByIndex(normalIndexes.get(i) - 1);
			}
			else {
				normal = new Vector3f();
			}
			
			Vector2f uvCoordinate;
			if (uvCoordinateIndexes.size() > 0) {
				uvCoordinate = group.getUVCoordinateByIndex(uvCoordinateIndexes.get(i) - 1);
			}
			else {
				uvCoordinate = new Vector2f();
			}
			
			points.add(position);
			
			addPolygonVertex(new Vertex3f(position, normal, uvCoordinate));
		}
		
		calculateBoundingVolume(points);
		
		if (calculateVertexesNormals) {
			calculateVertexesNormals();
		}
	}

	public void addNormalIndex(int index) {
		normalIndexes.add(index);
	}

	public void addUVCoordinateIndex(int index) {
		uvCoordinateIndexes.add(index);
	}

	public void addPositionIndex(int index) {
		positionIndexes.add(index);
	}

}